﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GridManager : MonoBehaviour
{
    public static GridManager Instance;
    private List<Vector2> pointlist = new List<Vector2>();
    private List<Grid> Gridlist = new List<Grid>();
    // Start is called before the first frame update

    private void Awake()
    {
        Instance = this;
    }
    void Start()
    {
        //CreatGridBase();
        //CreatGridsBasePointList();
        CreatGridsBaseGrid();

    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Debug.Log(GetPointByMouse());
        }
    }

    // Update is called once per frame
    private void CreatGridBase()
    {
        //这个预制体是植物网格
        GameObject prefabGrid = new GameObject();
        prefabGrid.AddComponent<BoxCollider2D>().size=new Vector2(1,1.5f);
        prefabGrid.transform.SetParent(transform);
        prefabGrid.transform.position = transform.position;
        prefabGrid.name = 0 + "-" + 0;

        for(int i = 0; i < 9; i++)
        {
            for(int j = 0; j < 5; j++)
            {
               GameObject grid = GameObject.Instantiate<GameObject>(prefabGrid, transform.position + new Vector3(1.33f*i, 1.63f*j), Quaternion.identity, transform);
                grid.name = i + "-" + j;
            }
        }
    }

    private void CreatGridsBasePointList()
    {
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                pointlist.Add(transform.position + new Vector3(1.33f * i, 1.63f * j));
            }
        }
    }
    private void CreatGridsBaseGrid()
    {
        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 5; j++)
            {
                Gridlist.Add(new Grid(new Vector2(i, j), transform.position + new Vector3(1.33f * i, 1.63f * j), false));
            }
        }
    }

    public Vector2 GetPointByMouse()
    {
        
        return GetPointByWorldPos(Camera.main.ScreenToWorldPoint(Input.mousePosition));
    }

    public Vector2 GetPointByWorldPos(Vector2 worldPos)
    {
        float dis = 1000000;
        Vector2 point = new Vector2();
        for (int i = 0; i < Gridlist.Count; i++)
        {
            if (Vector2.Distance(worldPos, Gridlist[i].position) < dis)
            {
                dis = Vector2.Distance(worldPos, Gridlist[i].position);
                point = Gridlist[i].position;
            }
        }
        return point;
    }
}
